﻿// See https://aka.ms/new-console-template for more information
using DotNetty.Buffers;
using Newtonsoft.Json;
using System.Net;
using System.Net.Sockets;
using System.Text;

int recv;
byte[] data = new byte[1024];

//构建TCP 服务器

//得到本机IP，设置TCP端口号         
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 8001);
Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

//绑定网络地址
newsock.Bind(ipep);

//得到客户机IP
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)(sender);
//发送信息
//newsock.SendTo(data, data.Length, SocketFlags.None, Remote);
var responseData = new
{
    reply = "UDPSerach",
    SN = "FC-8280T12345678",
    MAC = "00-11-22-33-44-55",
    IP = "192.168.1.130",
    Port = 8601
};

var responseStr = JsonConvert.SerializeObject(responseData);
var allocator = UnpooledByteBufferAllocator.Default;

var buf = allocator.Buffer(1024);

var jsonbuf=Encoding.UTF8.GetBytes(responseStr);
buf.WriteInt(jsonbuf.Length);
buf.WriteBytes(jsonbuf);
var responseBuf = buf.Array;
while (true)
{
    // data = new byte[1024];
    //发送接受信息
    recv = newsock.ReceiveFrom(data, ref Remote);
    buf.WriteBytes(data, 0, recv);

    var len = buf.ReadInt();
    var content = new byte[len];
    buf.ReadBytes(content);
    var sContent = Encoding.UTF8.GetString(content);
    Console.WriteLine(sContent);

    newsock.SendTo(responseBuf, responseBuf.Length, SocketFlags.None, Remote);
}